package com.yhgarden.bbs.service.impl.system;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yhgarden.bbs.entity.system.Entity;
import com.yhgarden.bbs.mapper.system.DatabaseMapper;
import com.yhgarden.bbs.mapper.system.EntityMapper;
import com.yhgarden.bbs.mapper.system.EntityPropertyMapper;
import com.yhgarden.bbs.model.enums.StatusCode;
import com.yhgarden.bbs.model.helper.Pager;
import com.yhgarden.bbs.model.helper.SortPointer;
import com.yhgarden.bbs.model.response.BaseResponse;
import com.yhgarden.bbs.service.api.system.EntityService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.UUID;

@Service
public class EntityServiceImpl implements EntityService {

    private static final Logger log= LoggerFactory.getLogger(EntityServiceImpl.class);

    @Autowired
    private EntityMapper entityMapper;

    @Autowired
    private EntityPropertyMapper entityPropertyMapper;

    @Autowired
    private DatabaseMapper databaseMapper;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public BaseResponse createOrUpdate(Entity entity) {
        BaseResponse response = new BaseResponse(StatusCode.SUCCESS);
        if ( entity.getId() == null ) {
            String uuid = UUID.randomUUID().toString();
            entity.setId(uuid);
            //根据表名查询实体对象，判断是否已经存在
            Entity oldEntity = entityMapper.getByTableName( entity.getTableName() );
            //如果实体已经存在，抛出
            if ( oldEntity != null ) {
                response = new BaseResponse(StatusCode.TABLE_IS_EXIT);
                return response;
            }
            //插入表记录
            entityMapper.create( entity );
            //创建物理表
            databaseMapper.createTable( entity.getTableName(), entity.getDescription() );
        } else {
            String entityId = entity.getId();
            Entity oldEntity = entityMapper.getById(entityId);
            String oldTableName = oldEntity.getTableName();
            String newTableName = entity.getTableName();
            //根据表名查询实体对象，判断是否已经存在
            Entity entityByTableName = entityMapper.getByTableName( newTableName );
            //直接更新表
            entityMapper.update(entity);
            //如果旧表名不等于新表名
            if(!oldTableName.equals(newTableName)){

                //如果实体已经存在，抛出
                if ( entityByTableName != null ) {
                    response = new BaseResponse(StatusCode.TABLE_IS_EXIT);
                    return response;
                }

                //更新表名
                databaseMapper.alterTableRename(oldTableName,newTableName);
                //更新表注释
                if(entity.getDescription() != null){
                    databaseMapper.alterTableComment(newTableName,entity.getDescription());
                }

            }else {
                //更新表注释
                if(entity.getDescription() != null){
                    databaseMapper.alterTableComment(oldTableName,entity.getDescription());
                }
            }
        }
        response.setData(entity);
        return response;
    }


    @Override
    public BaseResponse getById(String id) {
        BaseResponse response = new BaseResponse(StatusCode.SUCCESS);
        Entity entity = entityMapper.getById(id);
        response.setData(entity);
        return response;
    }


    @Override
    public BaseResponse getByIdMoreDetail(String id) {
        BaseResponse response = new BaseResponse(StatusCode.SUCCESS);
        Entity entity = entityMapper.getByIdMoreDetail(id);
        response.setData(entity);
        return response;
    }


    @Override
    public BaseResponse query(Entity entity) {
        BaseResponse response = new BaseResponse(StatusCode.SUCCESS);
        Pager pager = entity.getPager();
        SortPointer sortPointer = entity.getSortPointer();
        if(sortPointer == null){
            sortPointer = new SortPointer();
        }
        PageHelper.startPage(pager.getCurrentPage(),pager.getPageSize());
        List<Entity> entityList = entityMapper.query(entity,sortPointer.getOrder(),sortPointer.getField());
        PageInfo result = new PageInfo<Entity>(entityList);
        response.setData(result);
        return response;
    }


    @Override
    public BaseResponse queryMoreDetail(Entity entity) {
        BaseResponse response = new BaseResponse(StatusCode.SUCCESS);
        Pager pager = entity.getPager();
        SortPointer sortPointer = entity.getSortPointer();
        if(sortPointer == null){
            sortPointer = new SortPointer();
        }
        PageHelper.startPage(pager.getCurrentPage(),pager.getPageSize());
        List<Entity> entityList = entityMapper.queryMoreDetail(entity,sortPointer.getOrder(),sortPointer.getField());
        PageInfo result = new PageInfo<Entity>(entityList);
        response.setData(result);
        return response;
    }



    @Override
    public BaseResponse queryForList(Entity entity) {
        BaseResponse response = new BaseResponse(StatusCode.SUCCESS);
        Pager pager = entity.getPager();
        SortPointer sortPointer = entity.getSortPointer();
        if(sortPointer == null){
            sortPointer = new SortPointer();
        }
        PageHelper.startPage(pager.getCurrentPage(),pager.getPageSize());
        List<Entity> entityList = entityMapper.queryForList(entity,sortPointer.getOrder(),sortPointer.getField());
        PageInfo result = new PageInfo<Entity>(entityList);
        response.setData(result);
        return response;
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public BaseResponse delete(String id) {
        BaseResponse response = new BaseResponse(StatusCode.SUCCESS);
        //查询实体信息
        Entity entity = entityMapper.getById(id);
        //先删除实体属性
        entityPropertyMapper.deleteByEntityId(id);
        //删除实体
        entityMapper.delete(id);
        //删除物理表
        databaseMapper.dropTable(entity.getTableName());
        return response;
    }
}
